package com.notice.rule.print;

import ch.qos.logback.classic.spi.ILoggingEvent;
import com.notice.config.LogNoticeException;
import com.notice.entity.NoticePrint;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 消息加工工厂
 *
 * @author DZL
 * @date 2023/1/12 16:52
 */
public class LogNoticeMsgFactory {
    /**
     * 信息通知处理类
     */
    private static final List<AbstractNoticeMsgProcessHandler> MSG_NOTICE_SET = new ArrayList<>();

    /**
     * 默认的处理器
     */
    private static final List<String> DEFAULT_CLASS = Arrays.asList(
            HeadMsgProcess.class.getName(),
            StackMsgProcess.class.getName(),
            ErrorMsgProcess.class.getName(),
            RepeatMsgProcess.class.getName());

    /**
     * 添加消息加工器
     */
    static void addHandler(AbstractNoticeMsgProcessHandler handler) {
        if (handler.order() < 0 && !DEFAULT_CLASS.contains(handler.getClass().getName())) {
            throw new LogNoticeException("钉钉报警-自定义通知信息加载器order不可以<0");
        }
        MSG_NOTICE_SET.add(handler);
        if (MSG_NOTICE_SET.size() >= DEFAULT_CLASS.size()) {
            MSG_NOTICE_SET.sort(Comparator.comparingInt(AbstractNoticeMsgProcessHandler::order));
        }
    }

    /**
     * 日志信息打印结果
     *
     * @param event 错误节点
     * @return 打印结果
     */
    public static String print(ILoggingEvent event) {
        NoticePrint print = new NoticePrint();
        for (AbstractNoticeMsgProcessHandler processHandler : MSG_NOTICE_SET) {
            print = processHandler.printProcessing(event, print);
        }
        return print.getHeadMsg().concat(print.getErrorMsg()).concat(print.getStackMsg());
    }


}
